const BaseIpcHandler = require('../BaseIpcHandler');
const MapTileManager = require('../../map/MapTileManagerJimp');
const GoogleTileSystem = require('../../map/GoogleTileSystem');
const path = require('path');

class GetCaptureDirsHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> GetCaptureDirsHandler params = ', params);
        const { dir } = params;

        // 业务逻辑
        let result = null;

        // 定义输入截图目录和输出切片目录
        const captureDir = path.join(this.app.userDataPath, 'captures');
        const tileDir = path.join(this.app.userDataPath, 'tiles');

        // 初始化切片系统
        const tileSystem = new GoogleTileSystem(this.app);

        // 创建 MapTileManager 实例
        const processor = new MapTileManager(this.app, tileSystem);

        // 加载截图
        const screenshotsDir = path.join(captureDir, dir);
        const screenshots = await processor.loadScreenshots(screenshotsDir);
        if (screenshots.length === 0) {
            result = { code: -1, msg: '未找到有效的截图和元数据文件!' };
        } else {
            // 批量处理截图
            processor.batchProcess(screenshots, tileDir);
            result = { code: 0, msg: '开始批量处理截图...' };
        }

        // 返回结果
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = GetCaptureDirsHandler;
